package com.tyrone.concurrent.concurrentUtils;

import com.tyrone.concurrent.utils.SleepUtils;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Exchanger(交换者) 用于交换线程之间的数据交换
 * 应用场景：遗传算法，校对工作
 * @author Tyrone
 * @date 2021/12/22 23:55
 */
public class ExchangerTest {

    private static final Exchanger<String> exchanger = new Exchanger<>();

    private static ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(()->{
            /**
             * 逻辑处理
             */
            String threadAResult = "resultA";
            System.out.println(threadAResult);
            try {
                //调用exchange.exchange(）线程阻塞
                String exchange = exchanger.exchange(threadAResult);
                System.out.println("线程A-exchange:"+exchange);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        SleepUtils.second(5);
        threadPool.execute(()->{
            /**
             * 逻辑处理
             */
            String threadBResult = "resultB";
            System.out.println(threadBResult);
            SleepUtils.second(2);
            try {
                //调用exchange.exchange(）线程阻塞
                String threadAResult = exchanger.exchange(threadBResult);
                System.out.println("线程B-threadAResult:"+threadAResult);
                System.out.println(threadAResult.equals(threadBResult));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        threadPool.shutdown();
    }
}
